//
//  ApplyAuthenticationViewController.swift
//  Venus
//
//  Created by qurongxiang on 2018/8/4.
//  Copyright © 2018年 zhaowang. All rights reserved.
//

import UIKit
import SwiftyJSON

private let cellListID = "cellListID"
private let cellIDID = "cellIDID"
private let cellBookID = "cellBookID"


enum ApplyUpType{
    case JustID   //身份证正
    case BackID   //身份证反面
    case Book     //证书
}


class ApplyAuthenticationViewController: BaseViewController {
    
    fileprivate var uploadAlertController:UIAlertController!
    fileprivate var imagePickerController:UIImagePickerController!
    fileprivate var applyModel:ApplyModel =  ApplyModel()
    fileprivate var currentUpType:ApplyUpType = .JustID
    fileprivate var submitBtn:UIButton = UIButton(type: .custom)
    
    
    typealias okTypeBlock = () -> ()
  
    var backBlock : okTypeBlock?
  
    
    fileprivate lazy var tableView : UITableView = {
        let tableView = UITableView(frame: CGRect.zero)
        tableView.delegate = self
        tableView.dataSource = self
        tableView.separatorStyle = .none
        tableView.register(ApplyAuthListTableViewCell.self, forCellReuseIdentifier: cellListID)
        tableView.register(ApplyAuthIDTableViewCell.self, forCellReuseIdentifier: cellIDID)
        tableView.register(ApplyAuthBookTableViewCell.self, forCellReuseIdentifier: cellBookID)
        return tableView
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
        initAlertController()
        initImagePickerController()
    }
    
}


// MARK: - 网络请求
extension ApplyAuthenticationViewController {
    
    
    
    @objc func clickBtn(btn:UIButton) {
        applyModel.list[2].value = "机构"
        if applyModel.list[0].value.count == 0 || applyModel.list[1].value.count == 0 || applyModel.list[2].value.count == 0 {
            hudLoadMessage("基本信息不得为空")
            return
        }
        
        if applyModel.justUrl.count == 0 || applyModel.backUrl.count == 0  {
            hudLoadMessage("身份证必传")
            return
        }
        
        if applyModel.bookArr.count <= 1  {
            hudLoadMessage("证书必传")
            return
        }
        
        var resourceArr:[[String:String]] = [[String:String]]()
        resourceArr.append(["certificatePath": applyModel.justUrl,
                            "certificateType": "00"])
        resourceArr.append(["certificatePath": applyModel.backUrl,
                            "certificateType": "00"])
        
        for str in applyModel.bookArr  {
            if str.count > 0 {
                resourceArr.append(["certificatePath": str,
                                    "certificateType": "11"])
            }
        }
        let dict = [
            "userId":String(UserInfo.shareInstance.userModel().id),
            "userName":applyModel.list[0].value,
            "idCard":applyModel.list[1].value,
            "jobName":applyModel.list[2].value,
            "resource":resourceArr
            ] as [String : Any]
        self.hudLoad()
        TempNetTool.post(kHost + kapplyAuthentication + String().apiF(time: "1", sign: "1"), parameters: dict, progress: nil, success: { [weak self] (result) in
            if self?.backBlock != nil {
                self?.backBlock!()
            }
            self?.hudHide()
            self?.navigationController?.popViewController(animated: true)
        }) {  [weak self] (error) in
            self?.hudHide()
            self?.hudError()
        }
    }
}

// MARK: - 交互
extension  ApplyAuthenticationViewController: ApplyAuthIDTableViewCellDelegate,ApplyAuthBookTableViewCellDelegate {
    
    //删除第几个职业照片
    func clickApplyAuthBookDelIndex(index: Int) {
        applyModel.bookArr.remove(at: index)
        self.tableView.reloadData()
    }
    
    
    //点击身份证
    func clickApplyAuthID(index: Int) {
        if index == 0 { //正面
            currentUpType = .JustID
            present(self.uploadAlertController, animated:true, completion: nil)
        }else { //反面
            currentUpType = .BackID
            present(self.uploadAlertController, animated:true, completion: nil)
        }
    }
    
    //点击添加
    func clickApplyAuthBookIndex(index: Int) {
        
        if applyModel.bookArr.count == 6 {
            self.hudLoadMessage("最大五张")
            return
        }
        
        currentUpType = .Book
        present(self.uploadAlertController, animated:true, completion: nil)
    }
    
    
}

// MARK:- 代理
extension ApplyAuthenticationViewController:UITableViewDelegate , UITableViewDataSource {
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return 3
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return section == 0 ? 2:1
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if indexPath.section == 0 {
            let cell = tableView .dequeueReusableCell(withIdentifier: cellListID, for: indexPath) as! ApplyAuthListTableViewCell
            cell.configModel(modelArr: applyModel, index: indexPath)
            return cell
        }else if indexPath.section == 1 {
            let cell = tableView .dequeueReusableCell(withIdentifier: cellIDID, for: indexPath) as! ApplyAuthIDTableViewCell
            cell.delegate = self
            cell.config(model: applyModel, index: indexPath)
            return cell
        }else {
            let cell = tableView .dequeueReusableCell(withIdentifier: cellBookID, for: indexPath) as! ApplyAuthBookTableViewCell
            cell.delegate = self
            cell.config(model: applyModel, index: indexPath)
            return cell
        }
        
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        if indexPath.section == 0 {return 40}
        else if (indexPath.section == 1) {return ((LayoutCommon.width - 30)/2 + 10)}
        else {return 100}
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        if section == 0 { return nil }
        let headView = ApplyAuthHeadView(frame: CGRect.zero)
        headView.configModel(section: section)
        return headView
    }
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        let footView = UIView()
        footView.backgroundColor = kColorC2
        return footView
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        if section == 2 {return 0.001} else {return 10}
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        if section == 0 {
            return 0.001
        }
        return 30
    }
    
}

// MARK:-  相机 相册 代理
extension ApplyAuthenticationViewController:UIImagePickerControllerDelegate ,UINavigationControllerDelegate {
    
    func initAlertController() {
        weak var blockSelf = self
        self.uploadAlertController = UIAlertController(title:nil, message: nil, preferredStyle:UIAlertController.Style.actionSheet)
        let takePhoto = UIAlertAction(title:"拍照", style:UIAlertAction.Style.default) { (action:UIAlertAction)in
            blockSelf?.actionAction(action: action)
        }
        
        let photoLib = UIAlertAction(title:"从相册选择", style:UIAlertAction.Style.default) { (action:UIAlertAction)in
            blockSelf?.actionAction(action: action)
        }
        
        let cancel = UIAlertAction(title:"取消", style:UIAlertAction.Style.cancel) { (action:UIAlertAction)in
            blockSelf?.actionAction(action: action)
        }
        self.uploadAlertController?.addAction(takePhoto)
        self.uploadAlertController?.addAction(photoLib)
        self.uploadAlertController?.addAction(cancel)
        
    }
    
    func initImagePickerController() {
        self.imagePickerController = UIImagePickerController()
        self.imagePickerController.delegate = self
        self.imagePickerController.allowsEditing = true
    }
    
    
    func actionAction(action:UIAlertAction) {
        if action.title == "拍照" {
            self.getImageFromPhotoLib(type: .camera)
        }else if action.title == "从相册选择" || action.title == "更换头像" {
            self.getImageFromPhotoLib(type: .photoLibrary)
        }
    }
    
    func getImageFromPhotoLib(type:UIImagePickerController.SourceType) {
        self.imagePickerController.sourceType = type
        if UIImagePickerController.isSourceTypeAvailable(.photoLibrary) {
            self.present(self.imagePickerController, animated: true, completion:nil)
        }
    }
    
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
        
        let type:String = info[UIImagePickerController.InfoKey.mediaType] as! String
        if type=="public.image" {
            guard let img = info[UIImagePickerController.InfoKey.originalImage] as? UIImage else { return }
            let imgData =  img.jpegData(compressionQuality: 0.5)
            upLoad(data: imgData!)
            picker.dismiss(animated:true, completion:nil)
        }
    }
    
    func imagePickerControllerDidCancel(_ picker:UIImagePickerController){
        picker.dismiss(animated:true, completion:nil)
    }
    
    func upLoad(data:Data)  {
        self.hudLoad("上传中 请稍后")
        TempNetTool.get(kHost + kgetImgToken, parameters: ["timestamp":"11","sign":"22"], progress: nil, success: { (result) in
            let json = JSON(result ?? "")
            let token = json["uptoken"].string
            let upManager = QNUploadManager()
            upManager?.put(data, key: nil, token: token, complete: { [weak self](info, key, resp) in
                self?.hudHide()
                let json = JSON(resp as Any)
                let url = json["key"].stringValue
                if url.count > 0 {
                    if self?.currentUpType == .BackID {
                        self?.applyModel.backUrl = kqnImageHost + url
                        
                    }
                    if self?.currentUpType == .JustID {
                        self?.applyModel.justUrl = kqnImageHost + url
                    }
                    
                    if self?.currentUpType == .Book {
                        self?.applyModel.bookArr.insert(kqnImageHost + url, at: 0)
                    }
                    
                    self?.tableView.reloadData()
                }else {
                    self?.hudLoadMessage("网络异常")
                }
                
                }, option: nil)
        }) { [weak self](error) in
            self?.hudHide()
            self?.hudLoadMessage("网络异常")
        }
    }
}

extension ApplyAuthenticationViewController {
    func setupUI() {
        self.title = "申请认证"
        view.backgroundColor = UIColor.white
        view.addSubview(tableView)
        tableView.snp.makeConstraints { (make) in
            make.left.right.bottom.equalToSuperview()
            make.top.equalToSuperview().offset(LayoutCommon.navHeight)
        }
        
        let footView = UIView()
        footView.frame = CGRect(x: 0, y: 0, width: LayoutCommon.width, height: 50)
        tableView.tableFooterView = footView
        
        footView.addSubview(submitBtn)
        submitBtn.snp.makeConstraints { (make) in
            make.left.equalTo(view).offset(10)
            make.right.equalTo(view).inset(10)
            make.height.equalTo(40)
            make.bottom.equalToSuperview()
        }
        submitBtn.backgroundColor =  UIColor.init(hex:"17bbfe")
        submitBtn.setTitle("完成", for: .normal)
        submitBtn.titleLabel?.font = UIFont.systemFont(ofSize: 15)
        submitBtn.fastCornerRadius(value: 4)
        submitBtn.addTarget(self, action: #selector(clickBtn(btn:)), for: .touchUpInside)
     }
}



